package pl.edu.mimuw.mas.visualization;

import pl.edu.mimuw.mas.visualization.rendering.IRenderer;

import com.sun.opengl.util.Animator;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.opengl.GLCanvas;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Okno AWT z animatorem OpenGL.
 */
public final class Window {
	private static final int X_SIZE = 800;
	private static final int Y_SIZE = 600;
	
	private static final boolean RESIZABLE = true;

	private Logger log = LoggerFactory.getLogger(getClass());
	
	private Frame frame;
	private GLCanvas canvas;
	private Animator animator;
	
	private boolean visible = false;

	public Window(String title, int x, int y) {
		frame = new Frame(title);
		frame.setSize(x, y);
		frame.setResizable(RESIZABLE);

		canvas = new GLCanvas();
		frame.add(canvas);

		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {	}
		});		
	}
	
	public Window(String title) {
		this(title, X_SIZE, Y_SIZE);
	}

	public void attachRenderer(IRenderer listener) {
		canvas.addGLEventListener(listener);		
		animator = new Animator(canvas);
	}

	public void showWindow() {
		synchronized (this) {
			if (!visible) {
				animator.start();
				log.info("Start animacji");

				frame.setVisible(true);
				visible = true;
			}
		}
	}

	public void closeWindow() {
		synchronized (this) {
			if (visible) {
				animator.stop();
				log.info("Koniec animacji");

				frame.setVisible(false);
				visible = false;
			}
		}
		
		frame.dispose();
	}
}
